import React, { useState, useEffect } from "react";
import { SystemConfig } from "@/api/entities";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import {
  Settings,
  Brain,
  Plus,
  Save,
  RefreshCw,
  Trash2,
  Check,
  AlertTriangle,
  Users,
  BookOpen, // 字典相关图标
  ListChecks, // 字典条目相关图标
  FileText, // 导出变量相关图标
} from "lucide-react";

import LLMConfigManager from "../components/system-config/LLMConfigManager";
import SystemSettingsManager from "../components/system-config/SystemSettingsManager";
import ConfigTestPanel from "../components/system-config/ConfigTestPanel";
import DictionaryTypeManager from "../components/system-config/DictionaryTypeManager";
import DictionaryContentManager from "../components/system-config/DictionaryContentManager";
import ResponsiblePersonConfigManager from "../components/system-config/ResponsiblePersonConfigManager";
// 导入导出变量管理组件
import ExportVariableManager from "../components/system-config/ExportVariableManager";

export default function SystemConfigPage() {
  const [configs, setConfigs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("personnelRoles");
  const [saveStatus, setSaveStatus] = useState(null);
  const [activeDictTab, setActiveDictTab] = useState("dictionaryTypes");

  useEffect(() => {
    loadConfigs();
  }, []);

  const loadConfigs = async () => {
    setIsLoading(true);
    try {
      const configData = await SystemConfig.list("-updatedDate");
      setConfigs(Array.isArray(configData) ? configData : []);
    } catch (error) {
      console.error("加载系统配置失败:", error);
      setConfigs([]);
    }
    setIsLoading(false);
  };

  // 保存配置的处理方法（保持不变）
  const handleSaveConfig = async (configData, configId = null) => {
    try {
      setSaveStatus("saving");

      const duplicateConfig = configs.find(
        (c) => c.configKey === configData.configKey
      );

      if (configId) {
        // 更新模式
        if (duplicateConfig && duplicateConfig.id !== configId) {
          throw new Error(
            `配置键 '${configData.configKey}' 已被另一个配置使用，请使用唯一的键。`
          );
        }
        await SystemConfig.update(configId, configData);
      } else {
        // 创建模式
        if (duplicateConfig) {
          throw new Error(
            `配置键 '${configData.configKey}' 已存在，请使用唯一的键。`
          );
        }
        await SystemConfig.create(configData);
      }

      setSaveStatus("success");
      await loadConfigs();

      setTimeout(() => setSaveStatus(null), 3000);
    } catch (error) {
      console.error("保存配置失败:", error);
      setSaveStatus("error");
      alert(`保存失败: ${error.message}`);
      setTimeout(() => setSaveStatus(null), 3000);
    }
  };

  // 删除配置的处理方法（保持不变）
  const handleDeleteConfig = async (configId) => {
    if (window.confirm("确定要删除这个配置吗？此操作无法撤销。")) {
      try {
        await SystemConfig.delete(configId);
        await loadConfigs();
      } catch (error) {
        console.error("删除配置失败:", error);
        alert("删除配置失败，请稍后重试。");
      }
    }
  };

  // 设置默认配置的处理方法（保持不变）
  const handleSetDefault = async (configId, configKey) => {
    try {
      const sameTypeConfigs = configs.filter(
        (c) => c.configKey.startsWith(configKey.split("_")[0]) && c.isDefault
      );

      for (const config of sameTypeConfigs) {
        await SystemConfig.update(config.id, { ...config, isDefault: false });
      }

      const targetConfig = configs.find((c) => c.id === configId);
      await SystemConfig.update(configId, { ...targetConfig, isDefault: true });

      await loadConfigs();
    } catch (error) {
      console.error("设置默认配置失败:", error);
    }
  };

  // 数据过滤方法（增加导出变量的过滤）
  const getLLMConfigs = () => configs.filter((c) => c.configType === "llmModel");
  const getSystemSettings = () => configs.filter((c) => c.configType === "systemSetting");
  const getPersonnelRoles = () => configs.filter((c) => c.configType === "personnelRoles");
  const getDictionaryTypes = () => configs.filter((c) => c.configType === "dictionaryType");
  const getDictionaryContents = () => configs.filter((c) => c.configType === "dictionaryItem");
  const getExportVariables = () => configs.filter((c) => c.configType === "exportVariable");

  // 计算字典条目总数（保持不变）
  const getTotalDictionaryItems = () => {
    return getDictionaryContents().reduce((total, item) => {
      return total + (item.configValue?.items?.length || 0);
    }, 0);
  };

  // 渲染保存状态（保持不变）
  const renderSaveStatus = () => {
    if (!saveStatus) return null;

    const statusConfig = {
      saving: {
        icon: RefreshCw,
        text: "保存中...",
        color: "text-blue-600",
        bgColor: "bg-blue-50",
      },
      success: {
        icon: Check,
        text: "保存成功",
        color: "text-green-600",
        bgColor: "bg-green-50",
      },
      error: {
        icon: AlertTriangle,
        text: "保存失败",
        color: "text-red-600",
        bgColor: "bg-red-50",
      },
    };

    const config = statusConfig[saveStatus];
    const Icon = config.icon;

    return (
      <div
        className={`flex items-center gap-2 px-3 py-2 rounded-lg ${config.bgColor} ${config.color}`}
      >
        <Icon
          className={`w-4 h-4 ${saveStatus === "saving" ? "animate-spin" : ""}`}
        />
        <span className="text-sm font-medium">{config.text}</span>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto p-6">
        {/* 页面头部 */}
        <div className="mb-6 flex flex-col md:flex-row justify-between items-start gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2 flex items-center gap-2">
              <Settings className="w-6 h-6 text-blue-600" />
              系统配置
            </h1>
            <p className="text-gray-600">
              管理系统大模型配置、系统参数、责任人角色及字典数据
            </p>
          </div>

          <div className="flex items-center gap-3">
            {renderSaveStatus()}
            <Button
              onClick={loadConfigs}
              variant="outline"
              disabled={isLoading}
            >
              <RefreshCw
                className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`}
              />
              刷新配置
            </Button>
          </div>
        </div>

        {/* 主内容区 - 添加导出变量标签页 */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            {/* <TabsTrigger value="llmModels">大模型配置</TabsTrigger> */}
            <TabsTrigger value="personnelRoles">职位职责管理</TabsTrigger>
            <TabsTrigger value="dictionary">字典管理</TabsTrigger>
            <TabsTrigger value="exportVariables">导出变量管理</TabsTrigger>
          </TabsList>

          {/* 大模型配置标签页（保持不变） */}
          <TabsContent value="llmModels" className="mt-4">
            <LLMConfigManager
              configs={getLLMConfigs()}
              onSave={handleSaveConfig}
              onDelete={handleDeleteConfig}
              onSetDefault={handleSetDefault}
              isLoading={isLoading}
            />
          </TabsContent>

          {/* 责任人角色标签页（保持不变） */}
          <TabsContent value="personnelRoles" className="mt-4">
            <ResponsiblePersonConfigManager
              configs={getPersonnelRoles()}
              isLoading={isLoading}
            />
          </TabsContent>

          {/* 字典管理标签页（保持不变） */}
          <TabsContent value="dictionary" className="mt-4">
            <div className="mb-4">
              <Tabs value={activeDictTab} onValueChange={setActiveDictTab}>
                <TabsList className="mb-2">
                  <TabsTrigger value="dictionaryTypes">
                    字典类型管理
                  </TabsTrigger>
                  <TabsTrigger value="dictionaryContents">
                    字典内容管理
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="dictionaryTypes">
                  <DictionaryTypeManager
                    configs={getDictionaryTypes()}
                    onSave={handleSaveConfig}
                    onDelete={handleDeleteConfig}
                    isLoading={isLoading}
                  />
                </TabsContent>

                <TabsContent value="dictionaryContents">
                  <DictionaryContentManager
                    typeConfigs={getDictionaryTypes()}
                    contentConfigs={getDictionaryContents()}
                    onSave={handleSaveConfig}
                    onDelete={handleDeleteConfig}
                    isLoading={isLoading}
                  />
                </TabsContent>
              </Tabs>
            </div>
          </TabsContent>

          {/* 新增：导出变量管理标签页 */}
          <TabsContent value="exportVariables" className="mt-4">
            <ExportVariableManager
              configs={getExportVariables()}
              onSave={handleSaveConfig}
              onDelete={handleDeleteConfig}
              isLoading={isLoading}
            />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}